<template>
  <div class="home">
    <!-- 导航 -->
    <NavBar title="BDC" isFixed />
    <div class="contentview">
      <!-- 权限区域 -->
      <div v-if="isPermissions">
        <!-- 上报日志到服务端 -->
        <div>
          <div class="contentview-title">上报日志到服务端</div>
          <div
            class="items-center"
            style="flex-wrap: wrap; justify-content: space-between"
          >
            <van-button type="success" @click="isPermissionsClick(2)">
              添加过滤
            </van-button>
            <van-dialog
              v-model:show="ignoreKey.isShow"
              title="添加过滤"
              show-cancel-button
              @confirm="addIgnoreKey"
            >
              <van-field
                v-model="ignoreKey.text"
                type="text"
                maxlength="999"
                label="关键字"
              />
              <van-radio-group
                v-model="ignoreKey.isRegExp"
                class="items-center"
                style="padding: 10px 15px; justify-content: space-between"
              >
                <van-radio :name="1">非正则</van-radio>
                <van-radio :name="2">正则表达式</van-radio>
              </van-radio-group>
            </van-dialog>
          </div>
        </div>
      </div>
    </div>
    <!-- 公共区域 -->
    <div class="items-center" style="justify-content: space-around">
      <!-- 桥接测试 -->
      <van-button type="success" @click.stop="bridgeData.showPicker = true">
        桥接测试
      </van-button>
      <van-popup
        v-model:show="bridgeData.showPicker"
        destroy-on-close
        round
        position="bottom"
      >
        <van-picker
          title="标题"
          :model-value="bridgeData.pickerValue"
          :columns="bridgeData.columns"
          @confirm="onBridgeConfirm"
          @cancel="onBridgeCancel"
          @change="onBridgeChange"
        />
      </van-popup>

      <!-- 长安保存图片:app 端手势,h5 无需开发 -->
      <div
        v-if="false"
        class="items-center"
        style="justify-content: center; flex-direction: column"
      >
        <img style="width: 35px" :src="file.testImg" />
      </div>
    </div>

    <!-- 底部跳转 -->
    <div class="items-center jump">
      <div class="jump-btn" @click="jumpPage('coin')">coin</div>
      <div
        class="jump-btn"
        v-if="isPermissions"
        @click="jumpPage('exchangePoints')"
      >
        积分兑换
      </div>
      <div class="jump-btn" v-if="isPermissions" @click="jumpPage('log')">
        日志页面
      </div>
    </div>
  </div>
</template>
<script setup name="home">
import { navigateI18nTo, isiOS, isAndroid } from "@/utils";
import { JUMPAPPS } from "~/config";
import { useClipboard, usePermission } from "@vueuse/core";
import { loginUser } from "../api/user.ts";
// import { logStash } from "../api/elk.ts";

import {
  serveReport,
  getServeLog,
  removelog,
  errorkeyoperation,
  trackInfo,
} from "~/api/log.ts";
import { showToast } from "vant";
import { useUserStore } from "~~/store/modules/user";
import * as MITO from "@zhj1214/qdjk-web";
import { useLogStore } from "~~/store/modules/log";
// import { useGlobalStore } from "~~/store/global";

const file = getOssFileUrl({
  testImg: "/image/qrcode/xyx65.png?btcdanaAppH5Bridge=0426",
});

const route = useRoute();
console.log("页面参数:", route.query);
const userState = useUserStore();
// const globalStore = useGlobalStore();
const { WEB_NODE_ENV = "prod" } = useRuntimeConfig().public;

// 是否有权限访问数据
const isPermissions = computed(() => {
  if (userState.$state.email) {
    return (
      route.query.who === "zhj" && userState.$state.email.includes("zhj1214")
    );
  }
  return false;
});

// 生命周期函数
onMounted(() => {
  // logStash({
  //   test: "zhj1214",
  // }).then((res) => {
  //   console.log("res:", res);
  // });
  // bridgeTest()
});

// 桥接测试  { text: '杭州', value: 'Hangzhou' },
const bridgeTest = () => {
  if (JUMPAPPS()) {
    Object.keys(JUMPAPPS()).forEach((key) => {
      const val = JUMPAPPS()[key];
      if (typeof val == "function") {
        const valReturn = val();

        if (valReturn.routeKey) {
          console.log(key, "-- key-value:", valReturn);
          bridgeData.columns.push({
            value: valReturn.routeKey,
            text: valReturn.routeKey,
            params: valReturn,
          });
        } else {
          console.log(key, " -- 其他:", val);
        }
      } else if (typeof val == "string") {
        bridgeData.columns.push({
          value: JUMPAPPS()[key],
          text: JUMPAPPS()[key],
        });
      } else {
        console.log(key, " -- 其他:", val);
      }
    });
  }
};

// 获取 token
const getLoginToken = () => {
  if (WEB_NODE_ENV !== "prep" && route.query.who !== "zhj")
    return showToast("暂无权限");
  // 预发/生产环境
  loginUser({
    // deviceToken1: "about5best@gmail.com.",
    // password1: "a6851041",
    // uniqueId1: "about5best@gmail.com",
    // username1: "zhj1214mail@gmail.com",
    deviceToken: "zhj1214mail@gmail.com", // 推送token
    uniqueId: "zhj1214mail@gmail.com", // 设备唯一ID
    username: "zhj1214mail@gmail.com",
    lastLoginIp: "192.168.1.15",
    password: "a6851041",
  });
  // 测试环境
  //   curl --location 'https://api.okmax.vip/login' --header 'Package-Id: BtcDana-1.8.81-com.indone.online-android' --header 'Language: zh_hk' --header 'TimeZone: GMT+7' --header 'X-Real-IP: 1.1.1.1' --header 'X-Forwarded-For: 1.1.2.2' --header 'Content-Type: application/json' --header 'Cookie: JSESSIONID=E73B74C9DBD0D984D2244497816A88BD' --data-raw '{
  //     "deviceToken": "about28best@gmail.com",
  //     "password": "a6851041",
  //     "uniqueId": "about28best@gmail.com",
  //     "username": "zhj1214@hotmail.com.test"
  // }
  // '

  //     curl --location 'https://api.okmax.vip/login' --header 'Package-Id: BtcDana-1.8.81-com.indone.online-android' --header 'Language: zh_hk' --header 'TimeZone: GMT+7' --header 'X-Real-IP: 1.1.1.1' --header 'X-Forwarded-For: 1.1.2.2' --header 'Content-Type: application/json' --header 'Cookie: JSESSIONID=E73B74C9DBD0D984D2244497816A88BD' --data-raw '{
  //     "deviceToken": "berry@tradev-group.com",
  //     "password": "abc123456",
  //     "uniqueId": "berry@tradev-group.com",
  //     "username": "berry@tradev-group.com"
  // }
  // '
  // 300009@qq.com
  //     curl --location 'https://api.okmax.vip/login' --header 'Package-Id: BtcDana-1.8.81-com.indone.online-android' --header 'Language: zh_hk' --header 'TimeZone: GMT+7' --header 'X-Real-IP: 1.1.1.1' --header 'X-Forwarded-For: 1.1.2.2' --header 'Content-Type: application/json' --header 'Cookie: JSESSIONID=E73B74C9DBD0D984D2244497816A88BD' --data-raw '{
  //     "deviceToken": "202123497460@qq.com",
  //     "password": "AAbb301",
  //     "uniqueId": "202123497460@qq.com",
  //     "username": "202123497460@qq.com"
  // }
  // '

  //       curl --location 'https://api.okmax.vip/login' --header 'Package-Id: BtcDana-1.8.81-com.indone.online-android' --header 'Language: zh_hk' --header 'TimeZone: GMT+7' --header 'X-Real-IP: 1.1.1.1' --header 'X-Forwarded-For: 1.1.2.2' --header 'Content-Type: application/json' --header 'Cookie: JSESSIONID=E73B74C9DBD0D984D2244497816A88BD' --data-raw '{
  //     "deviceToken": "zhj11@qq.com",
  //     "password": "zhj123456",
  //     "uniqueId": "zhj11@qq.com",
  //     "username": "zhj11@qq.com"
  // }
  // '
};

/**
 * @description: 删除日志只保留部分数据
 */
const removeLog = reactive({
  isShow: false,
  num: 0,
});
const isPermissionsClick = (val) => {
  if (isPermissions.value) {
    if (val == 1) {
      removeLog.isShow = true;
    } else if (val == 2) {
      ignoreKey.isShow = true;
    }
  } else {
    showToast("暂无权限");
  }
};

// 过滤关键字
const ignoreKey = reactive({
  isShow: false,
  text: "",
  isRegExp: 1,
});
const addIgnoreKey = () => {
  if (!ignoreKey.text) return showToast("请输入关键字");
  // 去重
  const uselog = useLogStore();
  if (uselog.$state.ignoreDynamics.length > 0) {
    if (
      uselog.$state.ignoreDynamics.findIndex((e) => e == ignoreKey.text) != -1
    ) {
      return showToast("重复过滤");
    }
  }

  // 1: 不是  2: 是;   new RegExp('^abc')
  if (ignoreKey.isRegExp == 2) ignoreKey.text = `RegExp:${ignoreKey.text}`;

  errorkeyoperation({
    text: ignoreKey.text,
  }).then((res) => {
    showToast(res);
  });
};

// 点击-页面跳转
const jumpPage = async (val, isApp = false, params) => {
  if (isApp) {
    if (val === "taskCenter") {
      bridge.jumpAppRoute(JUMPAPPS()[val]);
    } else if (val === "hedgingWallet") {
    }
  } else if (val === "balance") {
    navigateI18nTo({
      path: "/mvp/assetDetails",
    });
  } else if (val === "mining") {
    navigateI18nTo({ path: "/mvp/mining" });
  } else if (val === "coin") {
    navigateI18nTo({
      path: "/mvp/coin/coin",
    });
  } else if (val === "exchangePoints") {
    navigateI18nTo({
      path: "/mvp/exchangePoints",
    });
  } else if (val === "web") {
    navigateI18nTo({
      path: "/webview",
      query: {
        src: `https://${pageData.jumpUrl}`,
      },
    });
  } else if (val === "log") {
    navigateI18nTo({
      path: "/log/errorlog",
      query: {
        who: "zhj",
      },
    });
  }
};

/****************************** 桥接测试 ******************************/
const bridgeData = reactive({
  columns: [
    {
      text: "分享",
      value: "分享",
    },
    {
      text: "登录",
      value: "登录",
    },
  ],
  showPicker: false,
  pickerValue: [""],
});

const onBridgeConfirm = ({ selectedValues }) => {
  console.log("selectedValues: ", selectedValues);
  if (selectedValues[0] == "分享") {
    bridge.onShare("桥接自测标题", window.location.href);
  } else if (selectedValues[0] == "登录") {
    globalStore.$state.isCallAppDone = true;
    bridge.onAppLogin();
  } else if (selectedValues[0] && typeof selectedValues[0] == "string") {
    bridge.jumpAppRoute(selectedValues[0]);
  } else if (selectedValues[0] && selectedValues[0].routeKey) {
    bridge.jumpAppRoute(
      selectedValues[0].routeKey,
      isAndroid.value,
      selectedValues[0].params
    );
  }
};

const onBridgeChange = ({ selectedValues }) => {
  // showToast(`当前值: ${selectedValues.join(",")}`);
};
const onBridgeCancel = () => {
  bridgeData.showPicker = false;
  showToast("取消");
};

/****************************** 上传图片 ******************************/
// params: Parameters<typeof uploadFileStream>[0] & {
//     type: 1 | 2 | 3; // 1: 身份证正面 2: 身份证反面 3" 手持身份证
//   }
const uploadFileStream = async (params) => {
  const nuxtApp = useNuxtApp();

  try {
    // 先图片压缩一下
    const image = await compressImage(params.image); //  as File;

    // 图片大小不能超过 1 M
    if (image.size > 1024 * 1024) {
      showToast(
        nuxtApp.$i18n.t("version_1_0_0.imageSizeCannotExceed", {
          num: 1,
        })
      );
      return;
    }

    if (params.type === 1) {
      if (this.firstLoading) {
        return;
      }

      this.firstLoading = true;
    } else if (params.type === 2) {
      if (this.lastLoading) {
        return;
      }

      this.lastLoading = true;
    } else if (params.type === 3) {
      if (this.threeLoading) {
        return;
      }

      this.threeLoading = true;
    }

    const result = await uploadFileStream({
      ...params,
      image,
    });

    if (result.code === 200) {
      if (params.type === 1 && result.data) {
        this.ruleForm.firstPic = result.data;
      } else if (params.type === 2 && result.data) {
        this.ruleForm.lastPic = result.data;
      } else if (params.type === 3 && result.data) {
        this.ruleForm.threePic = result.data;
      }
    } else {
      showToast(result.data.errors);
    }
  } catch (error) {
    console.log(error);
  } finally {
    if (params.type === 1) {
      this.firstLoading = false;
    } else if (params.type === 2) {
      this.lastLoading = false;
    } else if (params.type === 3) {
      this.threeLoading = false;
    }
  }
};

const getRoutes = () => {
  const router = useRouter();
  // 创建一个 Set 来存储唯一的 trackerId
  const routesSet = new Set();
  const routes = router.getRoutes().map((route) => route.path);

  routes.forEach((str) => {
    // 使用 split 分割字符串，然后重新组合
    const parts = str.split("/");
    if (parts.length > 2) {
      const result = "/" + parts.slice(2).join("/");
      routesSet.add(result);
    } else {
      console.log("字符串格式不符合预期");
    }
  });

  const routesArray = Array.from(routesSet);
  const jsonData = JSON.stringify(routesArray, null, 2); // 第二个参数和第三个参数用于格式化输出

  console.log("路由：", jsonData);
};
</script>
<style lang="scss" scoped>
.home {
  /* 禁止在整个页面范围内的溢出回弹效果 */
  overscroll-behavior-y: none !important;
  height: 100vh;
  overflow-y: scroll;
  overflow-x: hidden;

  .contentview {
    margin: 0 16 * 2px;

    &-title {
      font-size: 22 * 2px;
      font-weight: 666;
      margin: 10 * 2px;
    }
  }

  .jump {
    position: fixed;
    bottom: env(safe-area-inset-top);
    bottom: constant(safe-area-inset-top);
    bottom: 44px;
    left: 0;
    width: 100vw;
    justify-content: space-around;

    &-btn {
      padding: 10 * 2px 20 * 2px;
      background-color: #007bff;
      border-radius: 100px;
      text-align: center;
      font-size: 16 * 2px;
      color: #fff;
    }
  }
}
</style>
